<template>
  <div class="fullscreen-black">
    <dv-border-box11
      title="基于VR/AR市场洞察的大数据分析与交互式可视化平台"
      :title-width="800"
      :animate="false"
      class="main-border"
    >
      <el-row class="content-row">
        <!-- 左侧 -->
        <el-col :span="8" class="left-col">
          <div ref="marketSizeChartRef" class="chart-box"></div>
          <div ref="countryMarketChartRef" class="chart-box"></div>
          <v-chart class="chart-v" :option="barChartOptions" autoresize />
        </el-col>
  
        <!-- 中间 -->
        <el-col :span="8" class="center-col">
          <dv-decoration-9 class="logo-box">
            <div class="logo-wrapper">
              <img src="../assets/two.png" alt="VR Headset Logo" class="logo-image" />
            </div>
          </dv-decoration-9>
          <v-chart class="chart-v" :option="pieChartOptions" autoresize />
          <div ref="leftChart1" class="chart-box"></div>
        </el-col>
  
        <!-- 右侧 -->
        <el-col :span="8" class="right-col">
          <h3 class="chart-title">服务端IP流量分析</h3>
          <div ref="rightChart" class="chart-box"></div>
          <h3 class="chart-title">数据包大小分布</h3>
          <div ref="ringChart" class="chart-box"></div>
          <div ref="startupDistributionChartRef" class="chart-box"></div>
        </el-col>
      </el-row>
    </dv-border-box11>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart, BarChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components';
import VChart from 'vue-echarts';
import { BorderBox11 as DvBorderBox11, Decoration9 as DvDecoration9 } from '@kjgl77/datav-vue3';

use([CanvasRenderer, PieChart, BarChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent]);

const marketSizeChartRef = ref<HTMLDivElement | null>(null);
const countryMarketChartRef = ref<HTMLDivElement | null>(null);
const startupDistributionChartRef = ref<HTMLDivElement | null>(null);
const leftChart1 = ref<HTMLDivElement | null>(null);
const rightChart = ref<HTMLDivElement | null>(null);
const ringChart = ref<HTMLDivElement | null>(null);

// 初创公司分布数据
const startupData = [
  { country: 'United States', value: 40 },
  { country: 'United Kingdom', value: 21 },
  { country: 'India', value: 16 },
  { country: 'Austria', value: 12 },
  { country: 'China', value: 8 },
  { country: 'Germany', value: 8 },
  { country: 'Finland', value: 5 },
  { country: 'France', value: 3 },
  { country: 'Australia', value: 2 },
  { country: 'Denmark', value: 2 },
  { country: 'Spain', value: 2 },
  { country: 'Sweden', value: 2 },
  { country: 'Switzerland', value: 2 },
  { country: 'Taiwan', value: 2 },
  { country: 'Canada', value: 1 },
  { country: 'Iceland', value: 1 },
  { country: 'Ireland', value: 1 },
  { country: 'Lithuania', value: 1 },
  { country: 'South Korea', value: 1 }
];

// VR头显市场份额示例数据
const vrData = [
  { name: 'Oculus Quest 2', market_share: 55 },
  { name: 'HTC Vive', market_share: 15 },
  { name: 'Valve Index', market_share: 10 },
  { name: 'PlayStation VR', market_share: 5 },
  { name: 'Others', market_share: 15 }
];

// 饼图和柱状图配置
const pieChartOptions = {
  title: { text: 'VR Headset Market Share (Pie Chart)', left: 'center', textStyle: { color: '#fff' } },
  tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
  legend: {
    orient: 'vertical',
    right: '10%',
    top: 'middle',
    data: vrData.map(item => item.name),
    textStyle: { color: '#fff' }
  },
  series: [{
    name: 'Market Share',
    type: 'pie',
    radius: ['20%', '60%'],
    center: ['50%', '50%'],
    data: vrData.map(item => ({ value: item.market_share, name: item.name })),
    emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } },
    label: { color: '#fff', fontSize: 12, formatter: '{b}: {d}%' },
    itemStyle: { borderColor: '#0f1325', borderWidth: 2 }
  }]
};

const barChartOptions = {
  title: { text: 'VR Headset Market Share (Bar Chart)', left: 'center', textStyle: { color: '#fff' } },
  tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: '{b}: {c}%' },
  grid: { left: '10%', right: '10%', bottom: '15%', containLabel: true },
  xAxis: {
    type: 'category',
    data: vrData.map(item => item.name),
    axisLabel: { color: '#fff', rotate: 30, fontSize: 12 },
    axisTick: { alignWithLabel: true }
  },
  yAxis: { type: 'value', axisLabel: { color: '#fff' } },
  series: [{
    name: 'Market Share',
    type: 'bar',
    data: vrData.map(item => item.market_share),
    itemStyle: { color: '#67E0E3' },
    label: { show: true, position: 'top', color: '#fff' },
    barWidth: '50%'
  }]
};

// onMounted里面继续初始化图表（你原来的逻辑）
onMounted(() => {
  if (marketSizeChartRef.value) initMarketSizeChart();
  if (countryMarketChartRef.value) initCountryMarketChart();
  if (startupDistributionChartRef.value) initStartupDistributionChart();
  if (leftChart1.value) loadRadarChart();
  if (rightChart.value) loadChart2();
  if (ringChart.value) loadRingChart();
});

// 市场规模（折线图）
function initMarketSizeChart() {
  const chartDom = marketSizeChartRef.value!;
  const myChart = echarts.init(chartDom);
  const years = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024];
  const marketSizes = [3.41, 4.96, 7.21, 10.5, 15.26, 22.2, 32.27, 46.94, 68.28, 99.33];
  const option = {
    title: { text: 'VR/AR全球市场份额（亿美元）', left: 'center', textStyle: { color: '#fff' } },
    tooltip: { trigger: 'axis', axisPointer: { type: 'line' } },
    grid: { left: '3%', right: '10%', bottom: '3%', top: '20%', containLabel: true },
    xAxis: { type: 'category', data: years, axisLabel: { color: '#fff', rotate: 45 } },
    yAxis: { type: 'value', name: '市场份额（亿美元）', nameTextStyle: { color: '#fff' }, axisLabel: { color: '#fff' } },
    series: [{
      name: '市场份额',
      type: 'line',
      data: marketSizes,
      symbolSize: 8,
      itemStyle: { color: '#188df0' },
      lineStyle: { width: 3 },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(24, 141, 240, 0.8)' },
          { offset: 1, color: 'rgba(24, 141, 240, 0.3)' }
        ])
      },
      label: { show: true, position: 'top', formatter: '{c}', color: '#fff' }
    }]
  };
  myChart.setOption(option);
  window.addEventListener('resize', myChart.resize);
}

// 国家市场规模（饼图）
function initCountryMarketChart() {
  const chartDom = countryMarketChartRef.value!;
  const myChart = echarts.init(chartDom);
  const option = {
    title: { text: '2024年全球主要国家VR/AR市场规模', left: 'center', textStyle: { color: '#fff' } },
    tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c}亿美元 ({d}%)' },
    legend: { orient: 'vertical', left: 'left', textStyle: { color: '#fff' } },
    series: [{
      name: '市场规模',
      type: 'pie',
      radius: '60%',
      center: ['50%', '60%'],
      data: [
        { value: 12.6, name: '美国' },
        { value: 9.3, name: '中国' },
        { value: 2.358, name: '日本' },
        { value: 1.954, name: '德国' },
        { value: 1.458, name: '英国' },
        { value: 0.913, name: '韩国' }
      ],
      emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } },
      label: { color: '#fff', formatter: '{b}: {c}亿美元 ({d}%)' },
      labelLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.5)' } },
      itemStyle: { borderRadius: 10, borderColor: '#0f1354', borderWidth: 2 }
    }]
  };
  myChart.setOption(option);
  window.addEventListener('resize', myChart.resize);
}

// 初创公司分布（柱状图）
function initStartupDistributionChart() {
  const chartDom = startupDistributionChartRef.value!;
  const myChart = echarts.init(chartDom);
  const option = {
    title: { text: '2024-2025年全球VR/AR初创公司分布', left: 'center', textStyle: { color: '#fff' } },
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    xAxis: {
      type: 'value',
      name: '初创公司数量',
      nameTextStyle: { color: '#fff' },
      axisLabel: { color: '#fff' },
      splitLine: { lineStyle: { type: 'dashed' } }
    },
    yAxis: { type: 'category', inverse: true, axisLabel: { color: '#fff', fontSize: 14 } },
    series: [{
      type: 'bar',
      encode: { x: 'value', y: 'country' },
      label: { show: true, position: 'right', color: '#fff' },
      itemStyle: { color: '#188df0' }
    }],
    dataset: { source: startupData }
  };
  myChart.setOption(option);
  window.addEventListener('resize', myChart.resize);
}

// 雷达图（六大公司能力对比）
function loadRadarChart() {
  const myChart = echarts.init(leftChart1.value!);
  const companies = [
    { name: 'Meta (Quest)', color: '#1877f2', data: [9, 8, 9, 8, 9, 7] },
    { name: 'Apple (Vision Pro)', color: '#000000', data: [10, 9, 7, 10, 6, 8] },
    { name: 'Microsoft (HoloLens)', color: '#7cbb00', data: [8, 7, 6, 9, 5, 10] },
    { name: 'Sony (PS VR2)', color: '#003791', data: [8, 7, 8, 7, 7, 5] },
    { name: 'PICO (字节跳动)', color: '#ff3e30', data: [7, 6, 6, 6, 8, 6] },
    { name: 'HTC Vive', color: '#652d90', data: [7, 6, 7, 7, 4, 9] }
  ];
  const option = {
    backgroundColor: 'transparent',
    title: { text: '六大AR/VR公司能力对比', left: 'center', textStyle: { color: '#fff' } },
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0,0,0,0.7)',
      borderColor: 'rgba(255,255,255,0.5)',
      borderWidth: 1,
      formatter: (params: any) => `<strong style="color:${params.color}">${params.seriesName}</strong><br/>${params.name}: ${params.value}`
    },
    legend: { data: companies.map(c => c.name), bottom: 10, textStyle: { color: '#fff' }, itemWidth: 12, itemHeight: 12, itemGap: 10 },
    radar: {
      indicator: [
        { name: '硬件能力', max: 10 },
        { name: '软件生态', max: 10 },
        { name: '内容库', max: 10 },
        { name: '技术创新', max: 10 },
        { name: '市场份额', max: 10 },
        { name: '行业应用', max: 10 }
      ],
      radius: '60%',
      center: ['50%', '55%'],
      splitNumber: 4,
      axisName: { color: '#fff', fontSize: 12 },
      splitArea: { areaStyle: { color: ['rgba(255, 255, 255, 0.1)'] } },
      axisLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.3)' } },
      splitLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.3)' } }
    },
    series: [{
      type: 'radar',
      data: companies.map(company => ({
        value: company.data,
        name: company.name,
        areaStyle: { color: company.color, opacity: 0.3 },
        lineStyle: { color: company.color, width: 2 },
        symbol: 'circle',
        symbolSize: 6,
        label: { show: true, formatter: (params: any) => params.value, color: '#fff' }
      })),
      emphasis: { lineStyle: { width: 4 } }
    }]
  };
  myChart.setOption(option);
  window.addEventListener('resize', myChart.resize);
}

// 动态柱状图（IP地址流量）
function loadChart2() {
  let data = [400, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  const targetValues = [4060, 730, 140, 130, 120, 110, 100, 90, 80, 70];
  const colors = ['#37A2FF', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#FF9F7F', '#FB7293', '#E062AE', '#E690D1', '#E7BCF3'];
  const myChart = echarts.init(rightChart.value!);
  const option = {
    grid: { left: '15%', right: '10%', top: '15%', bottom: '10%', containLabel: true },
    xAxis: {
      max: 500,
      axisLabel: { color: '#fff', fontSize: 12 },
      axisLine: { lineStyle: { color: 'rgba(255,255,255,0.3)' } },
      splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
    },
    yAxis: {
      type: 'category',
      data: Array.from({length: 10}, (_, i) => `IP${i+1}`),
      inverse: true,
      axisLabel: { color: '#fff', fontSize: 12, margin: 20 },
      axisLine: { show: false },
      axisTick: { show: false }
    },
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        const index = parseInt(params.name.replace('IP', '')) - 1;
        const ips = ["200.18.102.102","142.251.129.195","142.251.128.138","52.209.66.100","142.250.79.202","142.251.132.46","142.250.218.238","142.251.132.238","23.10.53.152","2.18.127.238"];
        return `IP${index+1}: ${ips[index]}<br/>值: ${Math.floor(params.value)}`;
      }
    },
    series: [{
      realtimeSort: true,
      type: 'bar',
      data: data,
      label: { show: true, position: 'right', valueAnimation: true, color: '#fff', fontSize: 12, formatter: (params: any) => Math.floor(params.value) },
      itemStyle: {
        color: (params: any) => colors[params.dataIndex],
        borderRadius: 2,
        shadowBlur: 5,
        shadowColor: 'rgba(0,0,0,0.3)',
        shadowOffsetY: 2
      },
      barWidth: 16,
      emphasis: { itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0,0,0,0.5)' }, label: { fontWeight: 'bold' } }
    }],
    animationDuration: 800,
    animationDurationUpdate: 800,
    animationEasing: 'quadraticOut',
    animationEasingUpdate: 'quadraticOut'
  };
  myChart.setOption(option);

  // 更新数据动画
  const updateData = () => {
    let allReached = true;
    for (let i = 0; i < data.length; i++) {
      if (data[i] < targetValues[i]) {
        data[i] += targetValues[i] / 50;
        if (data[i] > targetValues[i]) data[i] = targetValues[i];
        allReached = false;
      }
    }
    const combined = data.map((v, idx) => ({ value: v, index: idx }));
    combined.sort((a, b) => b.value - a.value);
    const sortedData = combined.map(item => item.value);
    const sortedCategories = combined.map(item => `IP${item.index+1}`);
    const sortedColors = combined.map(item => colors[item.index]);

    myChart.setOption({
      yAxis: { data: sortedCategories },
      series: [{
        data: sortedData,
        itemStyle: { color: (params: any) => sortedColors[params.dataIndex] }
      }]
    });

    if (allReached) setTimeout(() => data = [400, 0, 0, 0, 0, 0, 0, 0, 0, 0], 2000);
  };
  const intervalId = setInterval(updateData, 1000 / 30);
  onUnmounted(() => clearInterval(intervalId));
}

// 动态环图（流量分布）
function loadRingChart() {
  const myChart = echarts.init(ringChart.value!);
  const total = 787;
  const ringData = [
    { value: 94, name: '0-1KB' },
    { value: 601, name: '1-10KB' },
    { value: 46, name: '10-100KB' },
    { value: 9, name: '100KB-1MB' },
    { value: 37, name: '1MB+' }
  ];
  let currentHighlightIndex = 0;
  let rotationAngle = 0;
  const colors = ['#FFD700','#FF6347','#2E8B57','#FF69B4','#4682B4'];

  const centerText = {
    type: 'text',
    left: 'center',
    top: 'center',
    style: { text: `${ringData[0].name}\\n${((ringData[0].value/total)*100).toFixed(2)}%`, textAlign: 'center', fill: '#fff', fontSize: 16, fontWeight: 'bold' },
    z: 100
  };
  const option = {
    tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
    legend: { top: '5%', left: 'center', textStyle: { color: '#fff' } },
    graphic: [centerText],
    series: [{
      name: 'Data Distribution',
      type: 'pie',
      radius: ['50%', '80%'],
      center: ['50%', '50%'],
      startAngle: 90,
      itemStyle: { borderRadius: 10, borderColor: '#0f1325', borderWidth: 2, shadowBlur: 5, shadowColor: 'rgba(0,0,0,0.3)' },
      label: { show: false },
      emphasis: { scale: true, scaleSize: 15 },
      labelLine: { show: false },
      data: ringData.map((item, index) => ({
        ...item,
        itemStyle: { color: colors[index % colors.length] }
      })),
      animationType: 'expansion',
      animationEasing: 'elasticOut',
      animationDuration: 1000
    }]
  };
  myChart.setOption(option);

  const highlightNext = () => {
    myChart.dispatchAction({ type: 'downplay', seriesIndex: 0, dataIndex: currentHighlightIndex });
    currentHighlightIndex = (currentHighlightIndex + 1) % ringData.length;
    myChart.dispatchAction({ type: 'highlight', seriesIndex: 0, dataIndex: currentHighlightIndex });
    centerText.style.text = `${ringData[currentHighlightIndex].name}\\n${((ringData[currentHighlightIndex].value/total)*100).toFixed(2)}%`;
    myChart.setOption({ graphic: [centerText] });
    rotationAngle += 5;
    myChart.setOption({ series: [{ startAngle: 90 + rotationAngle }] });
  };
  myChart.dispatchAction({ type: 'highlight', seriesIndex: 0, dataIndex: 0 });
  const intervalId = setInterval(highlightNext, 1000);
  onUnmounted(() => clearInterval(intervalId));
}
</script>

<style scoped>
.fullscreen-black {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgb(15, 19, 84);
  overflow: hidden;
}

.main-border {
  width: 98%;
  height: 96%;
  margin: 1% auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.content-row {
  width: 100%;
  height: 100%;
  margin-top: 2%; /* 整体向下移动一点 */
}

.el-col {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.left-col, .right-col {
  justify-content: space-between;
}

.center-col {
  justify-content: flex-start;
  align-items: center;
}

.chart-box {
  width: 90%;
  height: 28%;
  margin: 1% 0;
}

.chart-title {
  color: #fff;
  font-size: 18px;
  text-align: center;
  margin-bottom: 10px;
}

.logo-box {
  width: 50%;
  height: 25%;
  margin: 10px auto;
}

.logo-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo-image {
  width: 90%;
  height: 90%;
  object-fit: contain;
}

.chart-v {
  width: 90%;
  height: 28%;
  margin: 1% 0;
}
</style>